<?php
namespace app\admin\controller;


use app\admin\common\controller\Base;
use app\admin\common\model\Menu as MenuModel;
use think\Exception;
use think\facade\Request;

class Menu extends Base
{
    /*
     * 菜单列表
     */
    public function menuList(MenuModel $menuModel)
    {
        $menuDatas = $menuModel->getMenuRecursion();

        $this->assign('menuDatas',$menuDatas);
        return $this->fetch('menuList');
    }

    /*
     * 菜单添加
     */
    public function addMenu(MenuModel $menuModel)
    {
        $topMenu = $menuModel->getTopMenu();

        $this->assign('topMenu',$topMenu);
        return $this->fetch('addMenu');
    }

    /*
     * 添加菜单操作
     */
    public function addMenuDo(MenuModel $menuModel)
    {
        $params = Request::param();
        $rule = 'app\admin\validate\AddMenu';
        $result = $this->validate($params,$rule);

        if (true !== $result) {
            $this->error($result);
        }

        $res = $menuModel->addMenu($params);

        if ($res) {
            $this->success('添加成功','menuList');
        }

        $this->error('添加失败');
    }

    /*
     * 删除菜单操作
     */
    public function delMenu(MenuModel $menuModel)
    {
        $id = Request::param('id');

        try{
            if ($menuModel->delMenu($id)) {
                $this->success('删除成功','menuList');
            };
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

        $this->error('删除失败');
    }

    /*
     * 菜单编辑
     */
    public function editMenu(MenuModel $menuModel)
    {
        $id = Request::param('id');

        if (empty($id)) {
            $this->error('数据ID丢失');
        }

        $topMenu = $menuModel->getTopMenu();
        $info = $menuModel->getInfoById($id);

        $this->assign('topMenu',$topMenu);
        $this->assign('info',$info);

        return $this->fetch('editMenu');
    }

    /*
     * 编辑菜单操作
     */
    public function editMenuDo(MenuModel $menuModel)
    {
        $params = Request::param();
        $rule = 'app\admin\validate\EditMenu';
        $result = $this->validate($params,$rule);

        if (true !== $result) {
            $this->error($result);
        }

        $res = $menuModel->editMenu($params);

        if ($res) {
            $this->success('更新成功','menuList');
        }

        $this->error('更新失败');
    }
}